﻿package base.loader.show {
	import flash.display.Sprite;
	import flash.text.TextField;
	import flash.events.ProgressEvent;
	import com.greensock.TweenNano;
	
	public class LoaderProgress extends Sprite {
		
		public var tfPercent: TextField;
		private var countFramesTweenPercent: uint;
		public var ratioProgress: Number;
		private var prevRatioLoaded: Number;
		private var _basePosXTfPercent: Number;
		
		public function LoaderProgress(tfPercent: TextField = null, countFramesTweenPercent: uint = 5): void {
			this.countFramesTweenPercent = countFramesTweenPercent;
			this.initTfPercent(tfPercent);
			this.ratioProgress = this.prevRatioLoaded = 0;
			this.setLoadProgress(0);
		}
		
		private function initTfPercent(tfPercent: TextField = null): void {
			if (this.tfPercent == null) this.tfPercent = tfPercent;
			if (this.tfPercent != null) {
				tfPercent.x = Math.round(tfPercent.x);
				tfPercent.y = Math.round(tfPercent.y);
				this.tfPercent.text = "0 %";
				this.addChild(this.tfPercent);
				this.basePosXTfPercent = this.tfPercent.x + this.tfPercent.width / 2;
			}
		}
		
		protected function get basePosXTfPercent(): Number {
			return this._basePosXTfPercent;
		}
		
		protected function set basePosXTfPercent(value: Number): void {
			this._basePosXTfPercent = value;
			this.tfPercent.x =  value - this.tfPercent.width / 2;
		}
		
		public function onLoadProgress(event: ProgressEvent): void {
			var ratioLoaded: Number = event.bytesLoaded / event.bytesTotal;
			if (isNaN(ratioLoaded)) ratioLoaded = this.prevRatioLoaded;
			ratioLoaded = Math.max(0, Math.min(1, ratioLoaded));
			this.prevRatioLoaded = ratioLoaded;
			this.setLoadProgress(ratioLoaded);
		}
		
		public function setLoadProgress(ratioLoaded: Number): void {
			this.update();
			TweenNano.killTweensOf(this);
			TweenNano.to(this, this.countFramesTweenPercent, {ratioProgress: ratioLoaded, useFrames: true, onUpdate: this.update});
		}
		
		protected function update(): void {
			if (this.tfPercent) this.tfPercent.text = String(Math.round(ratioProgress * 100)) + "%";
			//trace("this.ratioProgress:" + this.ratioProgress);
		}
		
		public function destroy(): void {
		}
		
	}

}